<template>
  <el-card :body-style="{ paddong: '0px' }">
    <div class="container" ref="target"></div>
  </el-card>
</template>

<script setup>
import { defineProps, ref, onMounted, watch } from 'vue'
import { TableSheet } from '@antv/s2'
import { useI18n } from 'vue-i18n'
import { watchSwitchLang } from '@/utils/i18n'

const i18n = useI18n()

const props = defineProps({
  data: {
    type: Array,
    required: true
  }
})

const target = ref(null)
let s2
onMounted(() => {
  const s2Options = {
    // 宽度
    width: target.value.clientWidth,
    // 高度
    height: target.value.clientHeight,
    // 是否显示行号
    showSeriesNumber: true,
    // 条件模式配置
    conditions: {
      // 背景字段标记
      background: [
        {
          // 设置背景的字段
          field: 'balance',
          // 映射函数
          mapping: (value) => {
            return {
              fill: value > 0 ? '#f3fff3' : '#ffe7e7'
            }
          }
        }
      ]
    }
  }

  s2 = new TableSheet(target.value, {}, s2Options)
  console.log('s2', s2)
})

// 图表渲染
const renderChart = () => {
  const s2DataConfig = {
    fields: {
      columns: [
        'province',
        'city',
        'coverage',
        'receivable',
        'actual',
        'balance'
      ]
    },
    meta: [
      {
        field: 'province',
        name: i18n.t('msg.chart.sheetProvince')
      },
      {
        field: 'city',
        name: i18n.t('msg.chart.sheetCity')
      },
      {
        field: 'coverage',
        name: i18n.t('msg.chart.sheetCoverage')
      },
      {
        field: 'receivable',
        name: i18n.t('msg.chart.sheetReceivable')
      },
      {
        field: 'actual',
        name: i18n.t('msg.chart.sheetActual')
      },
      {
        field: 'balance',
        name: i18n.t('msg.chart.sheetBalance')
      }
    ],
    data: props.data
  }

  // 更新数据
  s2.setDataCfg(s2DataConfig)
  s2.render(true)
}
watch(
  () => props.data,
  () => {
    renderChart()
  }
)

/**
 * 监听语言变化
 */
watchSwitchLang(renderChart)
</script>

<style scoped lang="scss">
.container {
  height: 782px;
}
</style>
